<template>
  <div class="dashboard">
    <!-- 全屏加载状态 -->
    <div v-if="pageLoading" class="full-page-loading">
      <div class="loading-container">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <span>数据加载中，请稍候...</span>
      </div>
    </div>
    
    <template v-else>
      <!-- 数据概览卡片 -->
      <el-row :gutter="20" class="data-overview">
        <el-col :span="5">
          <el-card shadow="hover" class="data-card">
            <template #header>
              <div class="card-header">
                <span>总销售额</span>
                <el-tag size="small" type="success">月</el-tag>
              </div>
            </template>
            <div class="card-content">
              <div class="amount">¥{{ formatNumber(overview.totalSales) }}</div>
              <!-- <div class="trend">
                <span :class="['percentage', overview.salesTrend >= 0 ? 'up' : 'down']">
                  {{ overview.salesTrend >= 0 ? '+' : '' }}{{ overview.salesTrend }}%
                </span>
                <span class="label">较上月</span>
              </div> -->
            </div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card shadow="hover" class="data-card">
            <template #header>
              <div class="card-header">
                <span>订单数量</span>
                <el-tag size="small" type="warning">月</el-tag>
              </div>
            </template>
            <div class="card-content">
              <div class="amount">{{ overview.orderCount }}</div>
              <!-- <div class="trend">
                <span :class="['percentage', overview.orderTrend >= 0 ? 'up' : 'down']">
                  {{ overview.orderTrend >= 0 ? '+' : '' }}{{ overview.orderTrend }}%
                </span>
                <span class="label">较上月</span>
              </div> -->
            </div>
          </el-card>
        </el-col>
        <el-col :span="5">
          <el-card shadow="hover" class="data-card">
            <template #header>
              <div class="card-header">
                <span>用户数量</span>
                <el-tag size="small" type="info">总</el-tag>
              </div>
            </template>
            <div class="card-content">
              <div class="amount">{{ overview.userCount }}</div>
              <!-- <div class="trend">
                <span :class="['percentage', overview.userTrend >= 0 ? 'up' : 'down']">
                  {{ overview.userTrend >= 0 ? '+' : '' }}{{ overview.userTrend }}%
                </span>
                <span class="label">较上月</span>
              </div> -->
            </div>
          </el-card>
        </el-col>
        <el-col :span="5">
          <el-card shadow="hover" class="data-card">
            <template #header>
              <div class="card-header">
                <span>商品数量</span>
                <el-tag size="small" type="danger">总</el-tag>
              </div>
            </template>
            <div class="card-content">
              <div class="amount">{{ overview.goodsCount }}</div>
              <!-- <div class="trend">
                <span :class="['percentage', overview.goodsTrend >= 0 ? 'up' : 'down']">
                  {{ overview.goodsTrend >= 0 ? '+' : '' }}{{ overview.goodsTrend }}%
                </span>
                <span class="label">较上月</span>
              </div> -->
            </div>
          </el-card>
        </el-col>
        <el-col :span="5">
          <el-card shadow="hover" class="data-card">
            <template #header>
              <div class="card-header">
                <span>商铺数量</span>
                <el-tag size="small" type="primary">总</el-tag>
              </div>
            </template>
            <div class="card-content">
              <div class="amount">{{ overview.shopCount }}</div>
              <!-- <div class="trend">
                <span :class="['percentage', overview.shopTrend >= 0 ? 'up' : 'down']">
                  {{ overview.shopTrend >= 0 ? '+' : '' }}{{ overview.shopTrend }}%
                </span>
                <span class="label">较上月</span>
              </div> -->
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 图表区域 -->
      <el-row :gutter="20" class="charts-section">
        <el-col :span="16">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>销售趋势</span>
                <el-radio-group v-model="salesChartType" size="small">
                  <el-radio-button value="week">本周</el-radio-button>
                  <el-radio-button value="month">本月</el-radio-button>
                  <el-radio-button value="year">全年</el-radio-button>
                </el-radio-group>
              </div>
            </template>
            <div class="chart-container" ref="salesChartRef" style="height: 350px;"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>商品分类占比</span>
              </div>
            </template>
            <div class="chart-container" ref="categoryChartRef" style="height: 350px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 最近订单 -->
      <el-card class="recent-orders">
        <template #header>
          <div class="card-header">
            <span>最近订单</span>
            <el-button type="primary" link @click="router.push('/jiang/orders')">
              查看全部
            </el-button>
          </div>
        </template>
        <el-table :data="recentOrders" style="width: 100%" v-loading="loading">
          <el-table-column prop="orderNo" label="订单号" width="180" />
          <el-table-column prop="createTime" label="下单时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="payAmount" label="金额" width="120">
            <template #default="{ row }">
              ¥{{ formatNumber(row.payAmount) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getOrderStatusType(row.status)">
                {{ getOrderStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="recipientName" label="收件人" />
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                link
                @click="router.push(`/jiang/orders/${row.id}`)"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import service from '@/utils/request'
import { getDashboardCards } from '@/api/admin'
import { getCategoryPercent } from '@/api/goods'
import { getRecentOrderList, getSalesTrend } from '@/api/order'

const router = useRouter()
const loading = ref(false)
const pageLoading = ref(true)
const dataLoadFailed = ref(false)
const salesChartRef = ref(null)
const categoryChartRef = ref(null)
let salesChart = null
let categoryChart = null

// 从localStorage获取上次选择的图表类型，如果没有则使用默认值
const savedChartType = localStorage.getItem('dashboard_sales_chart_type') || 'month'
// 销售图表类型
const salesChartType = ref(savedChartType)

// 销售趋势数据
const salesTrendData = ref({
  xAxis: [],
  values: []
})

// 数据概览
const overview = ref({
  totalSales: 0,
  salesTrend: 0,
  orderCount: 0,
  orderTrend: 0,
  userCount: 0,
  userTrend: 0,
  goodsCount: 0,
  goodsTrend: 0,
  shopCount: 0,
  shopTrend: 0
})

// 最近订单
const recentOrders = ref([])

// 商品分类数据
const categoryData = ref([
  { value: 6, name: '电子产品' },
  { value: 3, name: '服装' },
  { value: 4, name: '食品' }
])

// 格式化数字
const formatNumber = (num) => {
  if (!num && num !== 0) return '0.00'
  return Number(num).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无'
  try {
    return new Date(date).toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (e) {
    return '日期格式错误'
  }
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  const types = {
    0: 'warning',   // 待付款
    1: 'info',      // 待发货
    2: 'primary',   // 待收货
    3: 'success',   // 已完成
    4: 'danger'     // 已取消
  }
  return types[status] || 'info'
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const texts = {
    0: '待付款',
    1: '待发货',
    2: '待收货',
    3: '已完成',
    4: '已取消'
  }
  return texts[status] || '未知'
}

// 存储所有定时器ID，方便统一清理
const timerIds = ref([])

// 安全的setTimeout，会自动记录timerID以便清理
const safeSetTimeout = (callback, delay) => {
  const timerId = setTimeout(() => {
    // 执行回调后从数组中移除
    const index = timerIds.value.indexOf(timerId)
    if (index > -1) {
      timerIds.value.splice(index, 1)
    }
    callback()
  }, delay)
  
  // 记录timerID
  timerIds.value.push(timerId)
  return timerId
}

// 清理所有定时器
const clearAllTimers = () => {
  timerIds.value.forEach(id => {
    clearTimeout(id)
  })
  timerIds.value = []
}

// 初始化销售趋势图表
const initSalesChart = () => {
  if (!salesChartRef.value) {
    console.error('销售趋势图表DOM元素不存在')
    return
  }
  
  console.log('初始化销售趋势图表', salesChartRef.value)
  
  try {
    // 先销毁之前的实例（如果存在）
    if (salesChart) {
      console.log('销毁旧的销售图表实例')
      // 先解绑所有事件，防止内存泄漏
      salesChart.off('click')
      salesChart.off('mouseover')
      salesChart.off('mouseout')
      salesChart.dispose()
      salesChart = null
    }
    
    // 使用节流选项初始化图表，提高性能
    salesChart = echarts.init(salesChartRef.value, null, {
      renderer: 'canvas', // 使用canvas渲染器，性能更好
      devicePixelRatio: window.devicePixelRatio, // 适配高分辨率屏幕
      throttle: 100 // 节流，减少渲染频率
    })
    
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br />{a}: ¥{c}',
        confine: true // 限制在图表区域内
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        axisLabel: {
          interval: 'auto' // 自动隐藏部分标签，避免重叠
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      series: [{
        name: '销售额',
        type: 'line',
        smooth: true,
        data: [0, 0, 0, 0, 0, 0, 0],
        areaStyle: {
          opacity: 0.1
        },
        itemStyle: {
          color: '#409EFF'
        },
        // 减少图形元素数量，优化性能
        symbolSize: 6,
        showSymbol: false
      }]
    }
    
    console.log('设置销售图表初始配置', option)
    salesChart.setOption(option)
  } catch (error) {
    console.error('初始化销售图表失败:', error)
    // 确保在出错时将图表实例设为null，避免后续操作出错
    salesChart = null
  }
}

// 初始化商品分类占比图表
const initCategoryChart = () => {
  if (!categoryChartRef.value) {
    console.error('分类图表DOM元素不存在')
    return
  }
  
  console.log('初始化分类图表', categoryData.value)
  
  try {
    // 先销毁之前的实例（如果存在）
    if (categoryChart) {
      console.log('销毁旧的分类图表实例')
      // 先解绑所有事件，防止内存泄漏
      categoryChart.off('click')
      categoryChart.off('mouseover')
      categoryChart.off('mouseout')
      categoryChart.dispose()
      categoryChart = null
    }
    
    // 使用节流选项初始化图表，提高性能
    categoryChart = echarts.init(categoryChartRef.value, null, {
      renderer: 'canvas', // 使用canvas渲染器，性能更好
      devicePixelRatio: window.devicePixelRatio, // 适配高分辨率屏幕
      throttle: 100 // 节流，减少渲染频率
    })
    
    // 使用直接的数据进行初始化
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
        confine: true // 限制在图表区域内
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        type: 'scroll',
        data: categoryData.value.map(item => item.name)
      },
      series: [{
        name: '商品数量',
        type: 'pie',
        radius: '50%',
        data: categoryData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          formatter: '{b}: {c} ({d}%)'
        }
      }]
    }
    
    console.log('设置图表配置', option)
    categoryChart.setOption(option)
  } catch (error) {
    console.error('初始化分类图表失败:', error)
    // 确保在出错时将图表实例设为null，避免后续操作出错
    categoryChart = null
  }
}

// 更新销售趋势图表
const updateSalesChart = () => {
  if (!salesChart) {
    console.error('销售图表实例不存在')
    return
  }
  
  console.log('更新销售趋势图表', salesTrendData.value)
  try {
    // 提供完整的配置
    const option = {
      tooltip: {
        trigger: 'axis',
        formatter: '{b}<br />{a}: ¥{c}'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: salesTrendData.value.xAxis
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '¥{value}'
        }
      },
      series: [{
        name: '销售额',
        type: 'line',
        smooth: true,
        data: salesTrendData.value.values,
        areaStyle: {
          opacity: 0.1
        },
        itemStyle: {
          color: '#409EFF'
        }
      }]
    }
    
    console.log('更新销售图表配置', option)
    
    // 使用完整配置更新图表
    salesChart.setOption(option, true)
    
    // 强制重新渲染
    salesChart.resize()
  } catch (error) {
    console.error('更新销售图表失败:', error)
  }
}

// 加载数据
const loadData = async () => {
  loading.value = true
  dataLoadFailed.value = false
  
  try {
    console.log('开始加载所有数据')
    
    // 使用Promise.all同时发起多个请求
    const [dashboardData, salesTrendData, ordersData, categoryDataResponse] = await Promise.all([
      // 获取概览数据
      getDashboardCards().catch(error => {
        console.error('获取概览数据失败:', error)
        return {}
      }),
      
      // 获取销售趋势数据
      getSalesTrend(salesChartType.value).catch(error => {
        console.error('获取销售趋势数据失败:', error)
        return []
      }),
      
      // 获取最近订单
      getRecentOrderList().catch(error => {
        console.error('获取最近订单失败:', error)
        return []
      }),
      
      // 获取商品分类占比数据
      getCategoryPercent().catch(error => {
        console.error('获取分类数据失败:', error)
        return { data: [] }
      })
    ])
    
    // 处理概览数据
    if (dashboardData) {
      overview.value = {
        totalSales: dashboardData.totalSales || 0,
        orderCount: dashboardData.orderNumber || 0,
        userCount: dashboardData.userNumber || 0,
        goodsCount: dashboardData.goodsNumber || 0,
        shopCount: dashboardData.shopNumber || 0
      }
    }
    
    // 处理销售趋势数据
    if (salesTrendData && Array.isArray(salesTrendData)) {
      processSalesTrendData(salesTrendData)
    }
    
    // 处理订单数据
    if (ordersData && Array.isArray(ordersData)) {
      recentOrders.value = ordersData
      console.log('处理后的订单数据:', recentOrders.value)
    }
    
    // 处理分类数据
    if (categoryDataResponse && Array.isArray(categoryDataResponse.data)) {
      console.log('收到的分类数据:', categoryDataResponse.data)
      categoryData.value = categoryDataResponse.data.map(item => ({
        value: item.goodsNumber,
        name: item.categoryName
      }))
      console.log('处理后的分类数据:', categoryData.value)
    }
    
    console.log('所有数据加载完成')
    
  } catch (error) {
    console.error('加载数据失败：', error)
    ElMessage.error('加载数据失败，请刷新重试')
    dataLoadFailed.value = true
  } finally {
    loading.value = false
    pageLoading.value = false
    
    // 确保DOM已更新后再初始化图表
    nextTick(() => {
      console.log('初始化图表')
      
      // 初始化销售图表
      if (salesChartRef.value) {
        initSalesChart()
        if (salesChart) {
          updateSalesChart()
        }
      }
      
      // 初始化分类图表
      if (categoryChartRef.value) {
        initCategoryChart()
      }
      
      // 强制重绘图表
      setTimeout(() => {
        if (salesChart) salesChart.resize()
        if (categoryChart) categoryChart.resize()
      }, 200)
    })
  }
}

// 处理销售趋势数据的函数
const processSalesTrendData = (trendData) => {
  console.log('处理销售趋势数据:', trendData)
  // 根据时间单位处理数据
  let xAxisData = []
  let valuesData = []
  
  if (salesChartType.value === 'year') {
    // 年度数据：确保12个月都有数据，并按月份顺序排列
    const monthData = {}
    const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
    
    // 初始化12个月的数据为0
    monthNames.forEach((month) => {
      monthData[month] = 0
    })
    
    // 填充实际数据
    trendData.forEach(item => {
      if (monthNames.includes(item.date)) {
        monthData[item.date] = item.sales || 0
      }
    })
    
    // 按月份顺序生成数据
    monthNames.forEach((month) => {
      xAxisData.push(month)
      valuesData.push(monthData[month])
    })
  } else if (salesChartType.value === 'month') {
    // 月度数据：确保当月所有日期都有数据
    const daysInMonth = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate()
    const dayData = {}
    const currentMonth = new Date().getMonth() + 1 // 当前月份 (1-12)
    
    // 初始化当月所有日期的数据为0
    for (let i = 1; i <= daysInMonth; i++) {
      const dayStr = `${String(currentMonth).padStart(2, '0')}-${String(i).padStart(2, '0')}`
      dayData[dayStr] = 0
    }
    
    // 填充实际数据
    trendData.forEach(item => {
      if (item.date && dayData.hasOwnProperty(item.date)) {
        dayData[item.date] = item.sales || 0
      } else if (item.date) {
        // 处理可能的其他格式，如 "06-1" 转为 "06-01"
        const parts = item.date.split('-')
        if (parts.length === 2) {
          const month = parts[0]
          const day = String(parseInt(parts[1])).padStart(2, '0')
          const formattedDate = `${month}-${day}`
          if (dayData.hasOwnProperty(formattedDate)) {
            dayData[formattedDate] = item.sales || 0
          } else {
            // 如果格式不匹配，尝试其他可能的格式
            const altFormattedDate = `${String(currentMonth).padStart(2, '0')}-${day}`
            if (dayData.hasOwnProperty(altFormattedDate)) {
              dayData[altFormattedDate] = item.sales || 0
            } else {
              console.warn('无法匹配日期格式:', item.date)
            }
          }
        }
      }
    })
    
    // 按日期顺序生成数据
    Object.keys(dayData).sort().forEach(day => {
      // 只显示日期部分 (例如 "06-01" 显示为 "1日")
      const displayDay = parseInt(day.split('-')[1]) + '日'
      xAxisData.push(displayDay)
      valuesData.push(dayData[day])
    })
  } else {
    // 周数据：假设格式为"周一"、"周二"等
    const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    const weekData = {}
    
    // 初始化一周的数据为0
    weekDays.forEach(day => {
      weekData[day] = 0
    })
    
    // 填充实际数据
    trendData.forEach(item => {
      if (weekDays.includes(item.date)) {
        weekData[item.date] = item.sales || 0
      }
    })
    
    // 按周一到周日顺序生成数据
    weekDays.forEach(day => {
      xAxisData.push(day)
      valuesData.push(weekData[day])
    })
  }
  
  console.log('处理后的销售趋势数据:', { xAxis: xAxisData, values: valuesData })
  salesTrendData.value = {
    xAxis: xAxisData,
    values: valuesData
  }
}

// 重新加载数据
const reloadData = async () => {
  pageLoading.value = true
  await loadData()
}

// 专门更新分类图表
const updateCategoryChart = () => {
  if (!categoryChart) {
    console.error('分类图表实例不存在')
    return
  }
  
  if (!categoryData.value || categoryData.value.length === 0) {
    console.warn('分类数据为空')
    return
  }
  
  console.log('更新分类图表数据:', categoryData.value)
  
  try {
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        type: 'scroll',
        data: categoryData.value.map(item => item.name)
      },
      series: [{
        name: '商品数量',
        type: 'pie',
        radius: '50%',
        data: categoryData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          show: true,
          formatter: '{b}: {c} ({d}%)'
        }
      }]
    }
    
    // 使用完整配置更新图表
    categoryChart.setOption(option, true)
    
    // 强制重新渲染
    categoryChart.resize()
  } catch (error) {
    console.error('更新分类图表失败:', error)
  }
}

// 监听窗口大小变化 - 使用节流函数
let resizeTimer = null;
const handleResize = () => {
  // 使用节流函数处理resize事件，避免频繁触发
  if (resizeTimer) {
    clearTimeout(resizeTimer);
  }
  
  resizeTimer = setTimeout(() => {
    if (salesChart) salesChart.resize();
    if (categoryChart) categoryChart.resize();
    resizeTimer = null;
  }, 200);
}

onMounted(() => {
  console.log('组件挂载')
  
  // 直接加载数据
  loadData()
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  console.log('组件卸载，销毁图表实例')
  window.removeEventListener('resize', handleResize)
  
  // 清理所有定时器
  clearAllTimers()
  
  // 清理resize节流定时器
  if (resizeTimer) {
    clearTimeout(resizeTimer)
    resizeTimer = null
  }
  
  // 确保销毁图表实例
  if (salesChart) {
    console.log('销毁销售图表实例')
    try {
      // 先解绑所有事件，防止内存泄漏
      salesChart.off('click')
      salesChart.off('mouseover')
      salesChart.off('mouseout')
      salesChart.dispose()
      salesChart = null
    } catch (error) {
      console.error('销毁销售图表实例失败:', error)
    }
  }
  
  if (categoryChart) {
    console.log('销毁分类图表实例')
    try {
      // 先解绑所有事件，防止内存泄漏
      categoryChart.off('click')
      categoryChart.off('mouseover')
      categoryChart.off('mouseout')
      categoryChart.dispose()
      categoryChart = null
    } catch (error) {
      console.error('销毁分类图表实例失败:', error)
    }
  }
})

// 监听销售图表类型变化
watch(salesChartType, (newType) => {
  console.log('销售图表类型变更为:', newType)
  
  // 保存当前选择到localStorage
  localStorage.setItem('dashboard_sales_chart_type', newType)
  
  // 显示加载状态但不阻止用户操作
  loading.value = true
  
  // 重新加载销售趋势数据
  getSalesTrend(newType).then(data => {
    if (data && Array.isArray(data)) {
      processSalesTrendData(data)
      
      // 确保在DOM更新后再操作图表
      nextTick(() => {
        console.log('尝试更新销售图表')
        // 检查销售图表是否需要初始化
        if (!salesChart && salesChartRef.value) {
          initSalesChart()
        }
        
        // 更新销售图表数据
        if (salesChart) {
          updateSalesChart()
          console.log('销售图表更新完成')
        } else {
          console.error('销售图表实例不存在，无法更新')
        }
        
        // 确保分类图表存在
        console.log('检查分类图表状态')
        if (!categoryChart && categoryChartRef.value) {
          console.log('初始化分类图表')
          initCategoryChart()
        }
        
        // 强制重绘两个图表
        setTimeout(() => {
          console.log('强制重绘图表')
          if (salesChart) {
            salesChart.resize()
          }
          if (categoryChart) {
            categoryChart.resize()
          }
        }, 200)
      })
    }
  }).catch(error => {
    console.error('获取销售趋势数据失败:', error)
  }).finally(() => {
    // 隐藏加载状态
    loading.value = false
  })
})
</script>

<style lang="scss" scoped>
.dashboard {
  position: relative;
  min-height: 400px;
  
  .full-page-loading {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(255, 255, 255, 0.7);
    z-index: 1000;
    display: flex;
    justify-content: center;
    align-items: center;
    
    .loading-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .loading-icon {
        font-size: 24px;
        animation: rotating 2s linear infinite;
        margin-bottom: 10px;
      }
    }
  }
  
  .data-overview {
    margin-bottom: 20px;
  }

  .data-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .card-content {
      .amount {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 8px;
      }

      .trend {
        display: flex;
        align-items: center;
        gap: 8px;

        .percentage {
          font-size: 14px;
          font-weight: bold;

          &.up {
            color: #67c23a;
          }

          &.down {
            color: #f56c6c;
          }
        }

        .label {
          color: #909399;
          font-size: 12px;
        }
      }
    }
  }

  .charts-section {
    margin-bottom: 20px;
  }

  .chart-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .chart-container {
      height: 350px;
    }
  }

  .recent-orders {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
